from datetime import datetime

from django.db.models import Sum
from rest_framework import viewsets, mixins
from rest_framework.decorators import api_view, action
from rest_framework.response import Response
from rest_framework import status

from common.paginatedViewMixin import PaginatedViewMixin
from common.standard_pagination import StandardPagination
from task.models import TaskLog
from utils import response_body_utils
from utils.response_body_utils import get_success_response, get_error_response
from . import models
from .models import Project  # 假设你有一个名为MyModel的模型
from .serializers import ProjectModelSerializer  # 假设你有一个对应的序列化器

# Create your views here.
from rest_framework.viewsets import GenericViewSet


class ProjectView(viewsets.GenericViewSet, PaginatedViewMixin):
    queryset = Project.objects.all().filter(is_deleted=0).order_by("-update_time")
    serializer_class = ProjectModelSerializer
    pagination_class = StandardPagination  # 使用自定义的分页类

    def list(self, request):
        projects = self.get_queryset()
        projects = ProjectModelSerializer(projects, many=True).data
        return get_success_response(projects)

    def page(self, request):
        get_queryset = self.get_queryset()
        if request.query_params.get("name"):
            get_queryset = get_queryset.filter(name__icontains=request.query_params.get("name"))
        return super().base_page(request, get_queryset)

    def add(self, request):
        name = request.data["name"]
        if self.get_queryset().filter(name=name).first():
            return get_error_response(response_body_utils.DATA_DUPLICATION)
        # 反序列化
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return get_success_response("")
        else:
            print(serializer.errors)
        return get_success_response("")

    def delete(self, request, **kwargs):
        project_id = kwargs.get("pk")
        if self.get_queryset().filter(id=project_id).first():
            self.get_queryset().filter(id=project_id).update(is_deleted=1)
            return get_success_response("")
        else:
            return get_error_response(response_body_utils.DATA_ABSENT)

    def update(self, request):
        req_data = request.data
        if self.get_queryset().filter(id=req_data["id"]).first():
            self.get_queryset().filter(id=req_data["id"]).update(**req_data)
            return get_success_response("")
        else:
            return get_error_response(response_body_utils.DATA_ABSENT)

    def single(self, request):
        return get_success_response("")


class DataBoardView(viewsets.GenericViewSet):
    queryset = None
    serializer_class = None

    def data_board_by_project(self, request):
        if request.GET.get("project_id"):
            project_info = Project.objects.get(id=request.GET.get("project_id"))
            project_info = ProjectModelSerializer(project_info)
            aggregate_result = TaskLog.objects.filter(project_id=request.GET.get("project_id")).aggregate(
                log_count=Sum(1),  # 注意：这里使用Sum(1)是一个技巧，但通常我们使用Count('*')
                group_total=Sum('group_total'),
                group_pass_total=Sum('group_pass_total'),
                group_failed_total=Sum('group_failed_total'),
                case_total=Sum('case_total'),
                case_failed_total=Sum('case_failed_total'),
                cass_pass_total=Sum('cass_pass_total'),  # 注意：这里可能是cass_pass_total的拼写错误，你应该确认字段名
                cass_skip_total=Sum('cass_skip_total'),
                time_consuming=Sum('time_consuming'),
            )
            data_board_by_project_info = {
                "project_info": project_info.data,
                "aggregate_result": aggregate_result
            }
        else:
            return get_error_response(response_body_utils.PARAMS_MISSING)
        return get_success_response(data_board_by_project_info)
